<?php
Yii::import('ext.sms.lib.EsendexSendService');


class ESms extends CApplicationComponent {

	const RESULT_OK='OK';
	const RESULT_ERR='Error';


	/**
	 * Your Username (normally an email address).
	 * @var string
	 */
	public $username;

	/**
	 * Your Password.
	 * @var string
	 */
	public $password;

	/**
	 * Account Reference (either your virtual mobile number, or EX account number).
	 * @var string
	 */
	public $accountReference;

	/**
	 * An alias that the message appears to come from (alphanumeric characters only,
	 * and must be less than 11 characters).
	 * @var string
	 */
	public $originator;



	/**
	 * The type of the message in the body (e.g. Text, SmartMessage, Binary or Unicode).
	 * @var string
	 */
	public $type = "Text";

	/**
	 * The amount of time in hours until the message expires if it cannot be delivered.
	 * @var unknown_type
	 */
	public $validityPeriod = 0;

	/**
	 * Whether use secure connection
	 * @var boolean
	 */
	public $isSecure = false;


	/**
	 * @var string
	 */
	public $certificate;

	private $_sendService;

	public function init(){
		parent::init();

	}


	/**
	 * @param recipients The mobile number(s) to send the message to (comma-separated).
	 * @param body The body of the message to send (must be less than 160 characters).
	 * @return false if the SMS was not successfully sent. an array of message IDs if the SMS was successfully sent.
	 */
	public function sendMessage($recipients,$body){
		return false;
		$result=$this->getSendService()->SendMessageFull($this->originator,$recipients,$body,$this->type,$this->certificate);
		if(!empty($result) && $result['Result']==self::RESULT_OK){
			$messageIds=split( ",", $result['MessageIDs'] );
			foreach($messageIds as $mid){
				$model=new SmsSendMessage();
				$model->messageId=$mid;
				$model->recipients=$recipients;
				$model->body=$body;
				$model->time=time();
				$model->save();
			}			
			return $messageIds;
		}else{
			return false;
		}
	}

	public function getMessageStatus($messageID){
		$result=$this->getSendService()->getMessageStatus($messageID);
		if(!empty($result) && $result['Result']==self::RESULT_OK){
			return $result['MessageStatus'];
		}else{
			return false;
		}
	}


	private function getSendService(){
		if($this->_sendService===null){
			$this->_sendService=new EsendexSendService( $this->username, $this->password, $this->accountReference, $this->isSecure, $this->certificate);
		}
		return $this->_sendService;
	}

	public function normalizePhone($phone){
		if(substr($phone,0,2)==='61'){
			$phone='0'.substr($phone,2);
		}
		return $phone;
	}
}